#include "edragbox.h"

eDragBox::eDragBox(int x, int y, int cr)
 : Fl_Box(x, y, 10, 10) {
  box(FL_THIN_DOWN_BOX);
  corner = cr;
}

//over-ridden draw method
void eDragBox::draw() {
  int xo = x();
  int yo = y();
  // Draw the button box
  draw_box(box(), color());
  // set the clip region so we only "tile" the box
  fl_push_clip(xo+1, yo+1, w()-3, h()-3);
  // tile the pixmap onto the button face... there must be a better way
  for(int i = 2; i <= w(); i += 6)
    for(int j = 2; j <= h(); j += 6)
      fl_draw_pixmap(grip_tile_xpm, (xo + i), (yo + j));
  fl_pop_clip();
} // draw

// over-ridden handle
int eDragBox::handle(int event) {
  int ret = Fl_Box::handle(event);
  int dx, dy, xr, yr;
  int xg, yg, wg, hg;
    main_win=(Cetele *)parent()->parent();
    eContainer *p=(eContainer *)parent();
    Form *pp=(Form *)main_win->parent()->parent();
  xr = Fl::event_x_root();
  yr = Fl::event_y_root();
  switch (event) {
  case FL_PUSH: // downclick in button stores cursor offsets
    x1 = xr;
    y1 = yr;
    pp->textX(p->kutumetin()->x());
    pp->textY(p->kutumetin()->y()-60);
    pp->textW(p->kutumetin()->w());
    pp->textH(p->kutumetin()->h());
    pp->textR(p->cr());
    pp->textG(p->cg());
    pp->textB(p->cb());
    pp->textAlpha(p->calpha());
    pp->textScrollv(p->cyatay());
    pp->textScrollh(p->cdikey());
    pp->textPage()->activate();
    pp->altpro()->value(pp->textPage());
    ret = 1;
    break;

  case FL_DRAG: // drag the button (and its parent group) around the screen
    dx = xr - x1; dy = yr - y1;
    x1 = xr; y1 = yr;
    xg = parent()->x();
    yg = parent()->y();
    wg = parent()->w();
    hg = parent()->h();
    pp->textX(p->kutumetin()->x());
    pp->textY(p->kutumetin()->y()-60);
    pp->textW(p->kutumetin()->w());
    pp->textH(p->kutumetin()->h());
    if(xg+dx>=main_win->x() && yg+dy>=main_win->y() && xg+dx<=main_win->w() && yg+dy<=main_win->h()-40)
    {
      // now resize/move the enclosing group
      // use the middle button to move the window
      if(Fl::event_button2()|| Fl::event_button3()) {
        parent()->position(xg+dx, yg+dy);
        main_win->parent()->redraw();
      }
      else { // treat as a resize
        if(corner == TL) {
          parent()->resize(xg+dx, yg+dy, wg-dx, hg-dy);
          main_win->parent()->redraw();
        }
        else if (corner == BR) {
          parent()->resize(xg, yg, wg+dx, hg+dy);
          main_win->parent()->parent()->redraw();
        }
      }
    }
    ret = 1;
    break;

  case FL_RELEASE:
    ret = 1;
    break;

  case FL_ENTER:
    fl_cursor(FL_CURSOR_MOVE);
    ret = 1;
    break;

  case FL_LEAVE:
    fl_cursor(FL_CURSOR_DEFAULT);
    ret = 1;
    break;
  case FL_FOCUS:
    ret=1;
    break;
  case FL_KEYDOWN:
        if(Fl::event_key()==FL_Delete)
            p->deletesil(true);
        break;
  default:
    break;
  }

  return ret;
}
